package com.tencent.qcloud.tim.demo.login;

import static com.tencent.qcloud.tim.demo.TIMAppService.TAG;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatButton;

import com.mob.MobSDK;
import com.tencent.qcloud.tim.demo.TIMAppService;
import com.tencent.qcloud.tim.demo.bean.UserInfo;
import com.tencent.qcloud.tim.demo.config.AppConfig;
import com.tencent.qcloud.tim.demo.main.MainActivity;
import com.tencent.qcloud.tim.demo.main.MainMinimalistActivity;
import com.tencent.qcloud.tim.demo.signature.GenerateTestUserSig;
import com.tencent.qcloud.tim.demo.utils.DBHelper;

import java.sql.SQLException;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import com.tencent.qcloud.tim.demo.R;
import com.tencent.qcloud.tim.demo.utils.DemoLog;
import com.tencent.qcloud.tim.demo.utils.TUIUtils;
import com.tencent.qcloud.tuicore.interfaces.TUICallback;
import com.tencent.qcloud.tuicore.util.ToastUtil;

import android.os.CountDownTimer;

public class MobSMSActivity extends AppCompatActivity implements View.OnClickListener {

    EventHandler eventHandler;
    EditText etPhone, etCode;
    AppCompatButton btnLogin;
    TextView  tvLink, tvTimer;
    CheckBox userAgreement;
    LinearLayout llLoginMethods;
    private CountDownTimer countDownTimer;  // 用于倒计时
    private static final int COUNTDOWN_TIME = 60000;  // 60秒倒计时

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.phone_login);
        MobSDK.submitPolicyGrantResult(true);
        init();
    }

    private void init() {
        etPhone = findViewById(R.id.etPhone);
        etCode = findViewById(R.id.etCode);
        btnLogin = findViewById(R.id.btnLogin);
        tvLink = findViewById(R.id.tvLink);
        tvTimer = findViewById(R.id.tvTimer);  // 添加一个显示倒计时的TextView
        userAgreement = findViewById(R.id.UserAgreement);

        btnLogin.setOnClickListener(this);
        tvTimer.setOnClickListener(this);
        tvLink.setOnClickListener(this);

        eventHandler = new EventHandler() {
            @Override
            public void afterEvent(int event, int result, Object data) {
                if (result == SMSSDK.RESULT_COMPLETE) {
                    if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                        // 获取验证码成功
                        runOnUiThread(() -> {
                            Toast.makeText(MobSMSActivity.this, "获取验证码成功", Toast.LENGTH_SHORT).show();
                            startCountDown();  // 获取验证码后启动倒计时
                        });
                    } else if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                        // 验证码验证成功
                        runOnUiThread(() -> {
                            Toast.makeText(MobSMSActivity.this, "验证码正确，登录成功", Toast.LENGTH_SHORT).show();
                            String phone = etPhone.getText().toString().trim();
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        if (DBHelper.findUserExist(phone)) {
                                            TIMAppService.getInstance().initBeforeLogin(0);
                                            runOnUiThread(() -> btnLogin.setEnabled(false));

                                            final String userID = etPhone.getText().toString();
                                            final String userSig = GenerateTestUserSig.genTestUserSig(etPhone.getText().toString());

                                            LoginWrapper.getInstance().loginIMSDK(MobSMSActivity.this, AppConfig.DEMO_SDK_APPID, userID, userSig, TUIUtils.getLoginConfig(), new TUICallback() {
                                                @Override
                                                public void onError(final int code, final String desc) {
                                                    runOnUiThread(() -> {
                                                        ToastUtil.toastLongMessage(getString(R.string.failed_login_tip) + ", errCode = " + code + ", errInfo = " + desc);
                                                        btnLogin.setEnabled(true);
                                                    });
                                                    DemoLog.i(TAG, "imLogin errorCode = " + code + ", errorInfo = " + desc);
                                                }

                                                @Override
                                                public void onSuccess() {
                                                    UserInfo.getInstance().setUserId(userID);
                                                    UserInfo.getInstance().setUserSig(userSig);
                                                    UserInfo.getInstance().setAutoLogin(true);
                                                    UserInfo.getInstance().setDebugLogin(true);

                                                    // 登录成功，跳转到主页面
                                                    runOnUiThread(() -> {
                                                        Intent intent;
                                                        if (AppConfig.DEMO_UI_STYLE == 0) {
                                                            intent = new Intent(MobSMSActivity.this, MainActivity.class);
                                                        } else {
                                                            intent = new Intent(MobSMSActivity.this, MainMinimalistActivity.class);
                                                        }
                                                        startActivity(intent);
                                                        TIMAppService.getInstance().registerPushManually();
                                                        finish();
                                                    });
                                                }
                                            });

                                        } else {
                                            //设置密码注册
                                            Intent intent = new Intent(MobSMSActivity.this, NewUserPasswordActivity.class);
                                            intent.putExtra("phone", phone); // 将手机号传递给设置密码页面
                                            startActivity(intent);
                                        }
                                    } catch (SQLException e) {
                                        throw new RuntimeException(e);
                                    }
                                }
                            }).start();
                        });
                    }
                } else {
                    // 验证码验证失败
                    runOnUiThread(() -> {
                        Toast.makeText(MobSMSActivity.this, "验证码错误/获取失败", Toast.LENGTH_SHORT).show();
                        Log.e("SMS SDK", "Error: " + data);
                    });
                }
            }
        };

        SMSSDK.registerEventHandler(eventHandler);
    }

    @Override
    public void onClick(View view) {
        String phone = etPhone.getText().toString().trim();
        String code = etCode.getText().toString().trim();

        switch (view.getId()) {
            case R.id.tvTimer:
                if (TextUtils.isEmpty(phone)) {
                    Toast.makeText(this, "请输入手机号码", Toast.LENGTH_SHORT).show();
                } else {
                    // Start SMS verification process
                    getVerificationCode("86", phone);
                }
                break;
            case R.id.btnLogin:
                if (TextUtils.isEmpty(phone)) {
                    Toast.makeText(this, "请输入手机号码", Toast.LENGTH_SHORT).show();
                } else if (TextUtils.isEmpty(code)) {
                    Toast.makeText(this, "请输入验证码", Toast.LENGTH_SHORT).show();
                } else if (!userAgreement.isChecked()) {
                    Toast.makeText(this, "请同意用户协议", Toast.LENGTH_SHORT).show();
                } else {
                    // Perform login logic here
                    submitVerificationCode("86", phone, code);
                }
                break;
            case R.id.tvLink:
                finish();
                break;
            default:
                break;
        }
    }

    private void submitVerificationCode(String country, String phone, String code) {
        if (TextUtils.isEmpty(code)) {
            Toast.makeText(this, "请输入验证码", Toast.LENGTH_SHORT).show();
            return;
        }

        Log.d("SMS SDK", "Attempting to submit verification code: Country: " + country + ", Phone: " + phone + ", Code: " + code);
        SMSSDK.submitVerificationCode(country, phone, code);
    }

    private void getVerificationCode(String country, String phone) {
        SMSSDK.getVerificationCode(country, phone);
    }

    private void startCountDown() {
        // 禁用按钮，防止重复点击
        tvTimer.setEnabled(false);

        // 开始倒计时
        countDownTimer = new CountDownTimer(COUNTDOWN_TIME, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                // 更新倒计时显示
                tvTimer.setText("剩余时间: " + millisUntilFinished / 1000 + "秒");
            }

            @Override
            public void onFinish() {
                // 倒计时完成，恢复按钮状态
                tvTimer.setEnabled(true);
                tvTimer.setText("获取验证码");
            }
        };
        countDownTimer.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SMSSDK.unregisterEventHandler(eventHandler);
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }

    // 按钮点击事件
    public void phoneToPassword(View view) {
        Intent intent = new Intent(MobSMSActivity.this, LoginActivity.class);
        startActivity(intent);
    }
}
